{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# sklearn Kmeans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.cluster import KMeans\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 0, 2, 2, 1, 2, 1, 1, 2, 2, 1, 0, 1, 0, 2, 0, 0, 0, 2, 0, 0, 0,\n",
       "       1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 2, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1,\n",
       "       1, 1, 0, 1, 0, 2, 0, 0, 2, 0, 0, 2, 2, 0, 1, 1, 0, 1, 0, 2, 0, 0,\n",
       "       1, 2, 2, 1, 1, 1, 2, 0, 2, 2, 2, 0, 2, 0, 2, 1, 1, 0, 0, 1, 2, 1,\n",
       "       2, 1, 2, 1, 1, 0, 1, 2, 1, 1, 1, 1])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = np.random.rand(100, 3)\n",
    "num_clusters = 3\n",
    "#假如我要构造一个聚类数为3的聚类器\n",
    "estimator = KMeans(n_clusters=3)#构造聚类器\n",
    "estimator.fit(data)#聚类\n",
    "label_pred = estimator.labels_ #获取聚类标签\n",
    "centroids = estimator.cluster_centers_ #获取聚类中心\n",
    "inertia = estimator.inertia_ # 获取聚类准则的总和\n",
    "label_pred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.27731049, 0.45306911, 0.19046162],\n",
       "       [0.78665949, 0.57327276, 0.46268025],\n",
       "       [0.22540225, 0.47739242, 0.76518987]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "centroids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "13.963346997928069"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "inertia"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
